<?php
/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 * 
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @package   App_User
 * @author    Cheng Wei <berlios.o@gmail.com>
 * @version   $$Id: User.php 20 2010-12-18 09:35:07Z cheng.wei $$
 * @copyright Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */

/**
 * Model for user
 * 
 * 
 * @see Evebit_Auth_Adapter_Frontend
 * 
 * @package   App_User
 * @author    Cheng Wei <berlios.o@gmail.com>
 * @version   $$Id: User.php 20 2010-12-18 09:35:07Z cheng.wei $$
 */
class User_Model_Entity_User extends Evebit_Model_Abstract {
	
	/**
	 * @return User_Model_Entity_User
	 */
	protected function _afterSave() {
		parent::_afterSave ();
		
		return $this;
	}
	
	/**
	 * @return User_Model_Entity_User
	 */
	protected function _beforeSave() {
		if (! $this->id) {
			$this->id = null;
		}
		if (! $this->id) {
			if (! $this->confirm_key) {
				$this->confirm_key = $this->getRandomKeys ();
			}
			if (! $this->state) {
				$this->state = 'confirming';
			}
			if (! $this->select_role) {
				$this->select_role = 'Entrepenuer';				
			}
			if($this->select_role == 'Entrepenuer'){
				$this->state = 'normal';
			}
		}
		if (! $this->lastest_modified) {
			$this->lastest_modified = time ();
		}
		return parent::_beforeSave ();
	}
	
	/**
	 * Processing object after delete data
	 *
	 * @return Et_Model_Abstract
	 */
	protected function _afterDelete() {
		parent::_afterDelete ();
		
		$event = new Evebit_Event ( 'delete_user', $this );
		$event->dispatch ();
		
		return $this;
	}
	
	protected function _beforeDelete() {
		parent::_beforeDelete ();
		//$this->getResource ()->_beforeDelete ( $this );
		

		return $this;
	}
	/**
	 * Get hash of password with salt
	 * 
	 * @param string $password
	 * @param string $salt
	 * 
	 * @return string
	 */
	public function getHash($password, $salt = null) {
		if ($salt) {
			$tokens = explode ( ":", $salt );
			if (count ( $tokens ) == 2) {
				$salt = substr ( $tokens [1], 0, 2 );
			} else {
				$salt = substr ( $tokens [0], 0, 2 );
			}
		}
		if (! $salt) {
			$salt = substr ( md5 ( time () . rand ( 0, 999 ) ), 0, 2 );
		}
		return md5 ( $password . $salt ) . ':' . $salt;
	}
	
	public function getResource() {
		return $this->_getResource ();
	}
	
	public function checkConfirmKey($key) {
		$this->load ( $key, 'confirm_key' );
		return $this->id ? true : false;
	}
	
	public function isTimeValid() {
		$lastestModified = $this->lastest_modified;
		$now = time ();
		return ($now - $lastestModified) > 60 * 30 ? false : true;
	}
	/**
	 * Check whether the name is valid for some one, 
	 * if check for new user, pass $id as null
	 * 
	 * @param string $value
	 * @param int $id
	 * 
	 * @return bool
	 */
	public function isUserNameValid($value, $id = null) {
		if (! $value) {
			return false;
		}
		return $this->getResource ()->isUniqueValid ( 'username', $value, intval ( $id ) );
	}
	
	/**
	 * Check whether the email is valid for some one, 
	 * if check for new user, pass $id as null
	 * 
	 * @param string $value
	 * @param int $id
	 * 
	 * @return bool
	 */
	public function isEmailValid($value, $id = null) {
		if (! $value) {
			return false;
		}
		return $this->getResource ()->isUniqueValid ( 'email', $value, intval ( $id ) );
	}
	
	public function validateEmail($email){		
		$exp = "^[a-z'0-9]+([._-][a-z'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
		if(eregi($exp,$email)){		  
		  if(checkdnsrr(array_pop(explode("@",$email)),"MX")){	  	
			return true;
		  }else{
			return false;
		  }
		}else{
		  return false;
		}
	}
	
	/**
	 * Check whether the confirm_key is valid for some one, 
	 * if check for new user, pass $id as null
	 * 
	 * @param string $value
	 * @param int $id
	 * 
	 * @return bool
	 */
	public function isConfirmkeyValid($value, $id = null) {
		if (! $value) {
			return false;
		}
		return $this->getResource ()->isUniqueValid ( 'confirm_key', $value, intval ( $id ) );
	}
	
	protected function _getResource() {
		
		if (! $this->_resourceName) {
			if (preg_match ( "|^(.+)_Model_Entity_(.+)$|", get_class ( $this ), $match )) {
				$this->_setResourceModel ( $match [1] . "_Model_Resource_" . $match [2] );
			} else {
				throw new Exception ( 'Resource is not set' );
			}
		}
		
		return $this->getResourceSingleton ( $this->_resourceName );
	}
	/**
	 * check Acl permition
	 * 
	 * @param string $password
	 * @param string $salt
	 * 
	 * @return string
	 */
	public function checkAcl($controller) {
		$controllerName = $controller->getRequest ()->getControllerName ();
		$actionName = $controller->getRequest ()->getActionName ();
		if ($actionName != "" && $actionName != "index") {
			$controllerName = $controllerName . "-" . $actionName;
		}
		$module = $controller->getRequest ()->getModuleName ();
		$scope = $controller->getInvokeArg ( 'bootstrap' )->getOption ( 'scope' );
		$resourceName = $scope . "-" . $module . "-" . $controllerName;
		
		$acl = Zend_Registry::get ( "Acl" );
		return $acl->isAllowed ( $this->getSelectRole (), $resourceName );
	}
	
	public function getFormField() {
		$fileds = parent::getFormField ( 'user' );
		foreach ( $fileds as $key => $filed ) {
			switch ($key) {
				case 'lastest_modified' :
				case 'confirm_key' :
					unset ( $fileds [$key] );
					break;
				case 'radio_sex' :
					$sexTypes = array ('male', 'female' );
					$fileds [$key] ['data'] = array_combine ( $sexTypes, $sexTypes );
					break;
				case 'select_role' :
					$roleTypes = $this->getRoleType ();
					$fileds [$key] ['data'] = array_combine ( $roleTypes, $roleTypes );
					break;
			}
		}
		return $fileds;
	}
	
	public function getRoleType() {
		$db = $this->getResource ()->getReadConnection ();
		$select = $db->select ()->from ( 'role', 'role_name' );
		return $db->fetchCol ( $select );
	}
	
	public function getRandomKeys($length = null) {
		$length = $length ? $length : '32';
		0;
		$output = '';
		$pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
		for($a = 0; $a < $length; $a ++) {
			$output .= $pattern {mt_rand ( 0, 35 )};
		}
		return $output;
	}
}
